package ld.pojo;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Liudao
 * @Date: 2022-08-02-15:14
 * @Description:
 */
@Data
public class cart {
    private Map<Integer,cartItlm> map = new HashMap<>();

    public void addCart(Product product) {
        //判断是否有此商品
        boolean b = map.containsKey(product.getPid());
        if (b){
            //得到购物项
            cartItlm cartItlm = map.get(product.getPid());
            //修改购买数量
            cartItlm.setNum(cartItlm.getNum() + 1);
            //修改小计
            cartItlm.setTotal(cartItlm.getTotal() + product.getPrice());
        }else{
            //直接添加
            cartItlm cartItlm = new cartItlm(1,product.getPrice(),product);
            map.put(product.getPid(),cartItlm);
        }
        //修改库存
        product.setQuantity(product.getQuantity()-1);
    }

    public void removeCart(Integer pid) {
        //不用判断直接根据id移除
        //恢复库存
        cartItlm cartItlm = map.get(pid);
        cartItlm.getProduct().setQuantity(cartItlm.getProduct().getQuantity()+cartItlm.getNum());
        //移除
        map.remove(pid);
    }

    public void clearCart() {
        for (cartItlm cartItlm : map.values()) {
            //得到关联的商品
            Product product = cartItlm.getProduct();
            //恢复库存
            product.setQuantity(product.getQuantity()+cartItlm.getNum());
            //清空map
            map.clear();
        }
    }
}
